package edu.zcmu.seckill.interceptor;

import com.google.common.util.concurrent.RateLimiter;
import edu.zcmu.seckill.exception.MyException;
import edu.zcmu.seckill.response.ResultCode;
import edu.zcmu.seckill.utils.IpAdrressUtil;
import edu.zcmu.seckill.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;


@Slf4j
public class RequestLimiterInterceptor implements HandlerInterceptor {
    //每秒放3000个令牌
    @Autowired
    RateLimiter rateLimiter;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //获取令牌,如果未获得则等待0.5秒
        boolean flag = rateLimiter.tryAcquire(1, 500, TimeUnit.MILLISECONDS);

        if (flag==true){
            return true;
        }else{
            log.info(IpAdrressUtil.getIpAddress(request) +"被限制访问");
            throw new MyException(ResultCode.ERROR,"你已被限流，请稍后访问");
        }


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
